package com.demo.paypalmanagement.service.impl;

import cn.hutool.core.lang.WeightRandom;
import cn.hutool.core.util.RandomUtil;
import com.demo.paypalmanagement.common.BuildQuery;
import com.demo.paypalmanagement.common.CommonUtils;
import com.demo.paypalmanagement.common.ResultMsg;
import com.demo.paypalmanagement.config.response.BizException;
import com.demo.paypalmanagement.convert.ProductsConvert;
import com.demo.paypalmanagement.model.entity.LotteryRecord;
import com.demo.paypalmanagement.model.entity.Products;
import com.demo.paypalmanagement.mapper.ProductsMapper;
import com.demo.paypalmanagement.model.entity.Users;
import com.demo.paypalmanagement.model.vo.ProductsVO;
import com.demo.paypalmanagement.service.IProductsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.paypalmanagement.service.IUsersService;
import com.demo.paypalmanagement.service.LotteryRecordService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 商品表，存储系统中的商品信息 服务实现类
 * </p>
 *
 * @author dayu
 * @since 2024-12-02
 */
@Service
public class ProductsServiceImpl extends ServiceImpl<ProductsMapper, Products> implements IProductsService {

    @Autowired
    private CommonUtils commonUtils;

    @Autowired
    private LotteryRecordService lotteryRecordService;

    @Autowired
    private IUsersService usersService;

    @Override
    public Products customSaveProduct(ProductsVO vo) throws IOException {
        //校验
        validate(vo);
        //上传文件
        String uploadUrl = commonUtils.getUploadUrl(vo.getMainFile());
        vo.setMainImage(uploadUrl);

        List<String> subList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(vo.getSubImgList())) {
            for (MultipartFile multipartFile : vo.getSubImgList()) {
                String subImgUrl = commonUtils.getUploadUrl(multipartFile);
                subList.add(subImgUrl);
            }
        }
        vo.setSubImages(subList.toString());
        vo.setProductCode(UUID.randomUUID().toString().split("-")[0]);
        Products products = ProductsConvert.INSTANCE.convertVOToEntity(vo);
        this.saveOrUpdate(products);
        return products;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ProductsVO lottery() {
        Users userInfo = commonUtils.getUserInfo();
        if (userInfo.getLotteryNum() <= 0) {
            throw new BizException(ResultMsg.LOTTERY_NUM_IS_NOT_ENOUGH.getMsg());
        }
        ProductsVO vo = new ProductsVO();
        vo.setIsActive(1);
        vo.setIsPrize(1);
        List<Products> list = this.list(BuildQuery.buildProductItemQuery(vo));
        if (CollectionUtils.isEmpty(list)) {
            throw new BizException(ResultMsg.PRIZE_IS_EMPTY.getMsg());
        }
        List<WeightRandom.WeightObj<Products>> prizeList = new ArrayList<>();
        for (Products products : list) {
            prizeList.add(new WeightRandom.WeightObj<>(products,StringUtils.isNotBlank(products.getWeight())?Integer.valueOf(products.getWeight()):1));
        }
        WeightRandom<Products> productsWeightRandom = RandomUtil.weightRandom(prizeList);
        Products prize = productsWeightRandom.next();
        if (ObjectUtils.isEmpty(prize)) {
            throw new BizException(ResultMsg.NO_PRIZE_SELECTED.getMsg());
        }
        ProductsVO productsVO = new ProductsVO();
        productsVO.setName(prize.getName());
        productsVO.setDescription(prize.getDescription());
        productsVO.setMainImage(prize.getMainImage());
        productsVO.setRandomNum(list.indexOf(prize)+1);
        LotteryRecord lotteryRecord = new LotteryRecord();
        lotteryRecord.setUserId(userInfo.getId());
        lotteryRecord.setCreatedAt(new Date());
        lotteryRecord.setProductsId(prize.getId());
        lotteryRecord.setIsWinning(1);
        if (ObjectUtils.isEmpty(prize.getStockQuantity()) || prize.getStockQuantity() <= 0) {
            throw new BizException(ResultMsg.STOCK_IS_NOT_ENOUGH.getMsg());
        }
        prize.setStockQuantity(prize.getStockQuantity() - 1);
        userInfo.setLotteryNum(userInfo.getLotteryNum()-1);
        lotteryRecordService.save(lotteryRecord);
        this.updateById(prize);
        usersService.updateById(userInfo);
        return productsVO;
    }

    void validate(ProductsVO vo) {
        if (ObjectUtils.isEmpty(vo)) {
            throw new BizException(ResultMsg.OBJECT_IS_EMPTY.getMsg());
        }
        if (StringUtils.isBlank(vo.getName())) {
            throw new BizException(ResultMsg.NAME_IS_EMPTY.getMsg());
        }
        if (ObjectUtils.isEmpty(vo.getId()) && ObjectUtils.isEmpty(vo.getMainFile())) {
            throw new BizException(ResultMsg.MAIN_IMG_IS_NULL.getMsg());
        }
    }
}
